package com.goldplusgold.tradedelay.app.trade.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.goldplusgold.support.lib.base.adapter.AdapterParentBase;
import com.goldplusgold.support.lib.widget.horizontallistview.SyncHorizontalScrollView;
import com.goldplusgold.tradedelay.app.R;
import com.goldplusgold.tradedelay.app.market.eventbus.TotalPositionProfitAndLossMessageEvent;
import com.goldplusgold.network.lib.http.protobuf.Market;
import com.goldplusgold.tradedelay.app.trade.activity.ProfitAndLossActivity;
import com.goldplusgold.tradedelay.app.trade.eventbus.ContractTypeEvent;
import com.goldplusgold.tradedelay.app.trade.fragment.TradeFragment;
import com.goldplusgold.tradedelay.app.trade.pojo.Position;
import com.goldplusgold.support.lib.utils.PixelDpUtils;
import com.goldplusgold.support.lib.utils.StringConvertNumber;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by admin on 2017/5/16.
 */

public class AdapterPosition extends AdapterParentBase<Position> implements AdapterView.OnItemClickListener, SyncHorizontalScrollView.OnScrollListenter {

    private double lastPrice = 0.00;
    private ArrayList<SyncHorizontalScrollView> mScrollViewList = new ArrayList<>();
    private double mTotalPositionProfitAndLoss = 0.00;
    private boolean mNoDisplayLayout;


    public AdapterPosition(Context ctx) {
        super(ctx);
    }

    public AdapterPosition(Context ctx, boolean displayLayout) {
        super(ctx);
        this.mNoDisplayLayout = displayLayout;

    }


    public void setQuoteDyna(Market.QuoteDyna quoteDyna) {
        Market.QuoteDyna mQuoteDyna = quoteDyna;

        if (mQuoteDyna != null) {
            lastPrice = StringConvertNumber.parseDouble(mQuoteDyna.getLastPrice());
        }
        mTotalPositionProfitAndLoss = 0.00;
        notifyDataSetChanged();
        EventBus.getDefault().post(new TotalPositionProfitAndLossMessageEvent(mTotalPositionProfitAndLoss));
    }


    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        if (convertView == null) {
            convertView = getLayoutInflater().inflate(R.layout.item_position, parent, false);
            holder = new AdapterPosition.ViewHolder(convertView);
            for (int i = 0; i < 6; i++) {
                View childView = getLayoutInflater().inflate(R.layout.item_horizontal_position, holder.mListViewPosition, false);
                holder.mListViewPosition.addView(childView);
            }
            holder.mFullEqualsLayout.setEnabled(false);
            mScrollViewList.add(holder.mSyncHorizontalScrollView);
            holder.mSyncHorizontalScrollView.setOnScrollListenter(this);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        final Position content = getItem(position);
        if (content != null) {
            // 合约代码
            final String prodCode = content.getProdCode();
            holder.mTextViewTitlePosition.setText(prodCode);
            holder.mTextViewTitlePosition.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
            int count = holder.mListViewPosition.getChildCount();
            final String longOrShort = content.getLongOrShort();
            final int canUseAmt = content.getCanUseAmt();
            for (int i = 0; i < count; i++) {
                View childView = holder.mListViewPosition.getChildAt(i);
                TextView item = (TextView) childView.findViewById(R.id.id_text_view_horizontal);
                item.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);

                switch (i) {
                    case 0:
                        //多空
                        item.setText(longOrShort);
                        break;
                    case 1:
                        //手数
                        item.setText(content.getAvailableAmtAndTotalAmt());
                        break;
                    case 2:
                        //开仓均价
                        item.setText(String.valueOf(content.getOpenAvgPrice()));
                        break;
                    case 3:
                        // 浮动盈亏
                        int openAvgPrice = content.getOpenAvgPrice();
                        setItem(item, longOrShort, prodCode, openAvgPrice, lastPrice, canUseAmt);
                        break;
                    case 4:
                        //持仓均价
                        item.setText(String.valueOf(content.getPosiAvgPrice()));
                        break;
                    case 5:
                        // 多：( 最新价 - 持仓均价 ) *持仓手数（黄金：*1000，迷你黄金：*100）
                        // 空：( 持仓均价 - 最新价 ) *持仓手数
                        int posiAvgPrice = content.getPosiAvgPrice();
                        setItem(item, longOrShort, prodCode, posiAvgPrice, lastPrice, canUseAmt);
                        double positionProfitAndLoss = 0.00;
                        switch (prodCode) {
                            case "Ag(T+D)":
                                positionProfitAndLoss = Math.abs(lastPrice - posiAvgPrice);
                                break;
                            case "Au(T+D)":
                                positionProfitAndLoss = Math.abs(lastPrice - posiAvgPrice) * 1000;
                                break;
                            case "mAu(T+D)":
                                positionProfitAndLoss = Math.abs(lastPrice - posiAvgPrice) * 100;
                                break;
                        }

                        mTotalPositionProfitAndLoss = mTotalPositionProfitAndLoss + positionProfitAndLoss;
                        break;
                }


            }
            if (content.getDisplayPosition()) {
                //EventBus.getDefault().post(new ContractTypeEvent(getItem(position).getProdCode(), getItem(position).getLongOrShort()));
                holder.mFullEqualsLayout.setVisibility(View.VISIBLE);
                holder.mTextViewFullEquals.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Fragment f = getFragment();
                        String price = "";
                        String volume = String.valueOf(canUseAmt);
                        String tradeTypeCode = "";
                        String tradeWay = "";
                        if (f != null && f instanceof TradeFragment) {
                            switch (longOrShort) {
                                case "多":
                                    // TD_CLOSE_LONG("4043", "平多"),
                                    tradeTypeCode = "4043";
                                    price = ((TradeFragment) f).soldOnePrice.getText().toString();
                                    tradeWay = "平多";
                                    break;
                                case "空":
                                    //TD_CLOSE_SHORT("4044", "平空");
                                    tradeTypeCode = "4044";
                                    price = ((TradeFragment) f).buyOnePrice.getText().toString();
                                    tradeWay = "平空";
                                    break;
                            }

                            ((TradeFragment) f).showOrderDialog(tradeTypeCode, prodCode, price, tradeWay, volume);
                        }
                    }
                });

                holder.mTextViewStopProfits.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //需要把当前条目的数据传递给止盈止损页面

                        Intent intent = new Intent(getContext(), ProfitAndLossActivity.class);
                        intent.putExtra("prodCode", content.getProdCode());
                        intent.putExtra("bearbullType", content.getLongOrShort());
                        intent.putExtra("lots", content.getCanUseAmt());
                        intent.putExtra("openAvgPrice", content.getOpenAvgPrice());
                        getContext().startActivity(intent);
                    }
                });
            } else {
                holder.mFullEqualsLayout.setVisibility(View.GONE);
            }

            if (!this.mNoDisplayLayout) {
                holder.mListViewPosition.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        itemDisplay(position);
                    }
                });
            }
        }
        //在最后：名词解释
        if (position == getCount() - 1 && !mNoDisplayLayout) {
            holder.mTextViewDefinitions.setVisibility(View.VISIBLE);

            holder.mTextViewDefinitions.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Fragment f = getFragment();
                    if (f != null && f instanceof TradeFragment) {
                        View popupWindow = LayoutInflater.from(getContext()).inflate(R.layout.popupwindow_noun_explaination, null);
                        final PopupWindow window = new PopupWindow(popupWindow);
                        TextView confirm = (TextView) popupWindow.findViewById(R.id.tv_confirm);
                        confirm.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                window.dismiss();
                            }
                        });
                        window.setWidth(PixelDpUtils.dip2px(getContext(), 290));
                        window.setHeight(PixelDpUtils.dip2px(getContext(), 290));
                        window.setOutsideTouchable(false);
                        window.setFocusable(true);
                        window.setBackgroundDrawable(new ColorDrawable(0x00000000));
                        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
                            @Override
                            public void onDismiss() {
                                WindowManager.LayoutParams lp = getFragment().getActivity().getWindow().getAttributes();
                                lp.alpha = 1.0f;
                                getFragment().getActivity().getWindow().setAttributes(lp);
                            }
                        });
                        WindowManager.LayoutParams lp = getFragment().getActivity().getWindow().getAttributes();
                        lp.alpha = 0.5f;
                        getFragment().getActivity().getWindow().setAttributes(lp);
                        window.showAtLocation(holder.mTextViewDefinitions, Gravity.CENTER, 0, 0);
                    }
                }
            });


        } else {
            holder.mTextViewDefinitions.setVisibility(View.GONE);
        }
        return convertView;
    }


    private void setItem(TextView item, String longOrShort, String prodCode, int avgPrice, double lastPrice, int canUseAmt) {
        double positionProfitAndLoss = 0.00;
        switch (prodCode) {
            case "Ag(T+D)":
                positionProfitAndLoss = getItemValue(longOrShort, avgPrice, lastPrice, canUseAmt);
                break;
            case "Au(T+D)":
                positionProfitAndLoss = getItemValue(longOrShort, avgPrice, lastPrice, canUseAmt) * 1000;
                break;
            case "mAu(T+D)":
                positionProfitAndLoss = getItemValue(longOrShort, avgPrice, lastPrice, canUseAmt) * 100;
                break;
        }

        mTotalPositionProfitAndLoss = mTotalPositionProfitAndLoss + positionProfitAndLoss;
        java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
        String value = df.format(positionProfitAndLoss);
        if (positionProfitAndLoss > 0) {
            item.setTextColor(getContext().getResources().getColor(R.color.shallow_red));
            // 持仓盈亏
            item.setText("+" + value);
        } else if (positionProfitAndLoss < 0) {
            item.setTextColor(getContext().getResources().getColor(R.color.color_price_down));
            item.setText(value);
        } else {
            item.setTextColor(getContext().getResources().getColor(R.color.td_color_gray_two));
            // 持仓盈亏
            item.setText(value);
        }
    }


    private double getItemValue(String longOrShort, int avgPrice, double lastPrice, int canUseAmt) {
        switch (longOrShort) {
            case "多":
                //多：( 最新价 - 开仓均价 ) *持仓手数
                return (lastPrice - avgPrice) * canUseAmt;
            case "空":
                //空：( 开仓均价 - 最新价 ) *持仓手数
                return (avgPrice - lastPrice) * canUseAmt;
        }
        return 0.00;
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        itemDisplay(position);
    }

    private void itemDisplay(int position) {
        Position content = getItem(position);
        if (content != null && content.getCanUseAmt() != 0) {
            int count = getCount();
            for (int i = 0; i < count; i++) {
                if (position == i) {
                    if (getItem(i).getDisplayPosition()) {
                        getItem(i).setDisplayPosition(false);
                        //持仓条目关闭时将平仓的价格按钮置为锁仓
                        Fragment fragment = getFragment();
                        if (fragment != null && fragment instanceof TradeFragment) {
                            ((TradeFragment) fragment).closePositionPrice.setText("锁 仓");
                        }
                    } else {
                        getItem(i).setDisplayPosition(true);
                        EventBus.getDefault().post(new ContractTypeEvent(getItem(position).getProdCode(), getItem(position).getLongOrShort()));
                    }
                } else {
                    getItem(i).setDisplayPosition(false);
                }
            }
            notifyDataSetChanged();
        }
    }


    @Override
    public void onScroll(int x, int y) {
        Log.e("xsy", "onScroll  x" + x);
        for (SyncHorizontalScrollView scrollview : mScrollViewList) {
            scrollview.setScrollX(x);

        }
    }

    public static class ViewHolder {
        @BindView(R.id.id_text_view_title_position)
        TextView mTextViewTitlePosition;
        @BindView(R.id.id_list_view_position)
        LinearLayout mListViewPosition;
        @BindView(R.id.content_horsv)
        SyncHorizontalScrollView mSyncHorizontalScrollView;

        @BindView(R.id.id_layout_full_equals) //bu
                LinearLayout mFullEqualsLayout;
        @BindView(R.id.id_text_view_full_equals) //bu
                TextView mTextViewFullEquals;
        @BindView(R.id.id_text_view_stop_profits_stop_losses) //bu
                TextView mTextViewStopProfits;
        @BindView(R.id.id_text_view_definitions) //bu
                TextView mTextViewDefinitions;


        public ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }


    public void addHead(SyncHorizontalScrollView view) {
        this.mScrollViewList.add(view);
    }


}
